<template>
  <div class="h-full flex flex-col lg:flex-row gap-6 overflow-hidden">
    <!-- Chat sessions sidebar (desktop) -->
    <div class="hidden lg:block w-80 flex-shrink-0">
      <div class="card h-full flex flex-col overflow-hidden">
        <!-- Sessions header -->
        <div class="flex items-center justify-between p-4 border-b border-gray-200 dark:border-dark-700">
          <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100">对话列表</h2>
          <button
            @click="chatStore.startNewSession"
            class="p-2 text-primary-600 dark:text-primary-400 hover:bg-primary-50 dark:hover:bg-primary-900/20 rounded-lg transition-colors"
            title="新建对话"
          >
            <PlusIcon class="w-5 h-5" />
          </button>
        </div>

        <!-- Sessions list -->
        <div class="flex-1 overflow-y-auto p-2 space-y-2">
          <div
            v-for="session in chatStore.sessions"
            :key="session.id"
            @click="chatStore.switchSession(session.id)"
            :class="[
              'p-3 rounded-lg cursor-pointer transition-all duration-200 group',
              {
                'bg-primary-50 dark:bg-primary-900/20 border-l-4 border-primary-500': chatStore.currentSession?.id === session.id,
                'hover:bg-gray-50 dark:hover:bg-dark-700': chatStore.currentSession?.id !== session.id
              }
            ]"
          >
            <div class="flex items-start justify-between">
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                  {{ session.title }}
                </p>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {{ formatTime(session.updated_at) }}
                </p>
                <div class="flex items-center space-x-3 mt-2">
                  <span class="text-xs text-gray-400 dark:text-gray-500">
                    {{ session.message_count }} 条消息
                  </span>
                  <span class="text-xs text-gray-400 dark:text-gray-500">
                    {{ session.token_usage }} tokens
                  </span>
                </div>
              </div>
              <button
                @click.stop="deleteSession(session.id)"
                class="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-red-500 transition-all duration-200"
                title="删除对话"
              >
                <TrashIcon class="w-4 h-4" />
              </button>
            </div>
          </div>

          <div
            v-if="chatStore.sessions.length === 0"
            class="text-center py-8 text-gray-500 dark:text-gray-400"
          >
            <ChatBubbleOvalLeftEllipsisIcon class="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p class="text-sm">暂无对话记录</p>
            <p class="text-xs mt-1">开始新的对话吧</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Main chat area -->
    <div class="flex-1 flex flex-col min-h-0 overflow-hidden">
      <div class="card flex-1 flex flex-col overflow-hidden">
        <!-- Chat header -->
        <div class="flex items-center justify-between p-4 border-b border-gray-200 dark:border-dark-700 flex-shrink-0">
          <div class="flex items-center space-x-3">
            <!-- Mobile sessions toggle -->
            <button
              @click="showMobileSessions = true"
              class="lg:hidden p-2 text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <Bars3Icon class="w-5 h-5" />
            </button>

            <div>
              <h1 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                {{ chatStore.currentSession?.title || 'AI助手' }}
              </h1>
              <p class="text-sm text-gray-500 dark:text-gray-400">
                智能ERP管理助手，随时为您提供帮助
              </p>
            </div>
          </div>

          <div class="flex items-center space-x-2">
            <!-- Theme suggestion button -->

            <!-- Clear chat button -->
            <button
              @click="clearChat"
              class="p-2 text-gray-500 dark:text-gray-400 hover:text-red-500 rounded-lg transition-colors"
              title="清空对话"
              :disabled="!chatStore.hasMessages"
            >
              <TrashIcon class="w-5 h-5" />
            </button>
          </div>
        </div>

        <!-- Messages area -->
        <div 
          ref="messagesContainer"
          class="chat-messages-container p-4 space-y-4"
          @scroll="handleScroll"
        >
          <!-- Loading more indicator -->
          <div v-if="loadingMore" class="text-center py-2">
            <div class="inline-flex items-center space-x-2 text-gray-500">
              <div class="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin"></div>
              <span class="text-sm">加载更多消息...</span>
            </div>
          </div>
          <!-- Welcome message -->
          <div v-if="!chatStore.hasMessages" class="text-center py-12">
            <div class="w-16 h-16 mx-auto mb-6 bg-gradient-primary rounded-2xl flex items-center justify-center glow-effect">
              <CpuChipIcon class="w-8 h-8 text-white" />
            </div>
            <h2 class="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
              欢迎使用 X-Synergy OS AI助手
            </h2>
            <p class="text-gray-600 dark:text-gray-400 mb-8 max-w-2xl mx-auto">
              我是您的智能ERP管理助手，可以帮助您查询数据、生成报表、分析业务趋势，以及回答各种业务问题。
            </p>

            <!-- Quick actions -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 max-w-4xl mx-auto">
              <button
                v-for="action in quickActions"
                :key="action.title"
                @click="sendQuickMessage(action.message)"
                class="p-4 text-left rounded-lg border border-gray-200 dark:border-dark-600 hover:border-primary-500 dark:hover:border-primary-400 hover:bg-primary-50 dark:hover:bg-primary-900/10 transition-all duration-200"
              >
                <component :is="action.icon" class="w-6 h-6 mb-3 text-primary-500" />
                <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-1">
                  {{ action.title }}
                </h3>
                <p class="text-xs text-gray-600 dark:text-gray-400">
                  {{ action.description }}
                </p>
              </button>
            </div>
          </div>

          <!-- Chat messages -->
          <div
            v-for="(message, index) in chatStore.currentMessages"
            :key="`${message.session_id}-${index}`"
            :class="[
              'flex',
              message.role === 'user' ? 'justify-end' : 'justify-start'
            ]"
          >
            <div
              :class="[
                'max-w-3xl rounded-lg px-4 py-3 animate-slide-up',
                {
                  'message-user ml-12': message.role === 'user',
                  'message-assistant mr-12': message.role === 'assistant',
                  'message-system mx-12': message.role === 'system'
                }
              ]"
            >
              <!-- Message header -->
              <div class="flex items-center justify-between mb-2" v-if="message.role !== 'user'">
                <div class="flex items-center space-x-2">
                  <div class="w-6 h-6 bg-gradient-primary rounded-full flex items-center justify-center">
                    <CpuChipIcon class="w-4 h-4 text-white" />
                  </div>
                  <span class="text-xs font-medium text-gray-600 dark:text-gray-400">
                    AI助手
                  </span>
                </div>
                <span class="text-xs text-gray-400 dark:text-gray-500">
                  {{ formatTime(message.timestamp) }}
                </span>
              </div>

              <!-- Message content -->
              <!-- 结构化数据渲染 -->
              <div v-if="message.messageType === 'table' && message.data" class="mb-4">
                <!-- 基于表格配置的动态表格 -->
                <div v-if="message.data.table_id" class="dynamic-table-container">
                  <div class="table-header mb-3">
                    <h4 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                      {{ message.data.title }}
                    </h4>
                    <p v-if="message.data.description" class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                      {{ message.data.description }}
                    </p>
                  </div>
                  
                  <VexTable
                    :columns="formatTableColumns(message.data.columns)"
                    :data="message.data.rows"
                    :loading="false"
                    :pagination="message.data.pagination"
                    :show-toolbar="true"
                    :show-search="message.data.config?.searchable_columns?.length > 0"
                    :show-refresh="false"
                    :export-enabled="message.data.config?.export_enabled"
                    :batch-operations="message.data.config?.batch_operations"
                    @export="exportDynamicTableData(message.data)"
                    @row-click="handleRowClick"
                  />
                </div>
                
                <!-- 传统表格数据（向后兼容） -->
                <DataTable 
                  v-else
                  :table-data="message.data"
                  :show-actions="true"
                  @export="exportTableData(message.data)"
                  @generateChart="generateChart(message.data)"
                />
              </div>
              
              <!-- 操作结果渲染 -->
              <div v-else-if="message.messageType === 'action' && message.data" class="mb-4">
                <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
                  <div class="flex items-center">
                    <svg class="w-5 h-5 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                    </svg>
                    <h4 class="text-green-800 dark:text-green-200 font-medium">操作执行成功</h4>
                  </div>
                  <p class="text-green-700 dark:text-green-300 mt-2">{{ message.data.message }}</p>
                  <div v-if="message.data.sql" class="mt-3 bg-gray-900 rounded p-3 text-green-400 font-mono text-sm">
                    {{ message.data.sql }}
                  </div>
                </div>
              </div>
              
              <!-- 普通文本消息 -->
              <div v-else
                class="markdown-content"
                v-html="formatMessageContent(message.content || '')"
              ></div>

              <!-- Message actions -->
              <div class="flex items-center justify-between mt-3" v-if="message.role === 'assistant'">
                <div class="flex items-center space-x-2">
                  <button
                    @click="copyMessage(message.content)"
                    class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                    title="复制消息"
                  >
                    <ClipboardIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="retryMessage()"
                    class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                    title="重新生成"
                  >
                    <ArrowPathIcon class="w-4 h-4" />
                  </button>
                </div>
                <span class="text-xs text-gray-400 dark:text-gray-500">
                  {{ formatTime(message.timestamp) }}
                </span>
              </div>
            </div>
          </div>

          <!-- Typing indicator -->
          <div
            v-if="chatStore.typing"
            class="flex justify-start animate-slide-up"
          >
            <div class="max-w-3xl mr-12 message-assistant rounded-lg px-4 py-3">
              <div class="flex items-center space-x-2">
                <div class="w-6 h-6 bg-gradient-primary rounded-full flex items-center justify-center">
                  <CpuChipIcon class="w-4 h-4 text-white" />
                </div>
                <span class="text-sm text-gray-600 dark:text-gray-400">
                  AI助手正在思考
                </span>
                <div class="typing-dots"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- Input area -->
        <div class="border-t border-gray-200 dark:border-dark-700 p-4 flex-shrink-0">
          <form @submit.prevent="sendMessage" class="flex space-x-3">
            <div class="flex-1 relative">
              <textarea
                ref="messageInput"
                v-model="messageText"
                placeholder="输入您的问题..."
                rows="1"
                class="input-primary resize-none min-h-[48px] max-h-32 leading-6 py-3"
                :disabled="chatStore.loading"
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.enter.shift.exact="newLine"
                @input="adjustTextareaHeight"
              ></textarea>
              
              <!-- Input actions -->
              <div class="absolute right-2 bottom-2 flex items-center space-x-1">
                <button
                  v-if="messageText.trim()"
                  @click="messageText = ''"
                  type="button"
                  class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                  title="清空输入"
                >
                  <XMarkIcon class="w-4 h-4" />
                </button>
              </div>
            </div>

            <button
              type="submit"
              :disabled="!messageText.trim() || chatStore.loading"
              class="btn-primary px-6 py-3 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <PaperAirplaneIcon 
                v-if="!chatStore.loading"
                class="w-5 h-5" 
              />
              <div 
                v-else
                class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"
              ></div>
            </button>
          </form>

          <div class="flex items-center justify-between mt-3 text-xs text-gray-500 dark:text-gray-400">
            <span>
              按 Enter 发送，Shift + Enter 换行
            </span>
            <span v-if="chatStore.tokenUsage > 0">
              本次会话已使用 {{ chatStore.tokenUsage }} tokens
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- Mobile sessions modal -->
    <div
      v-if="showMobileSessions"
      class="lg:hidden fixed inset-0 z-50 flex"
    >
      <div
        class="absolute inset-0 bg-black opacity-50"
        @click="showMobileSessions = false"
      ></div>
      <div class="relative w-80 max-w-sm bg-white dark:bg-dark-800 h-full">
        <div class="flex items-center justify-between p-4 border-b border-gray-200 dark:border-dark-700">
          <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100">对话列表</h2>
          <button
            @click="showMobileSessions = false"
            class="p-2 text-gray-500 dark:text-gray-400"
          >
            <XMarkIcon class="w-5 h-5" />
          </button>
        </div>
        
        <div class="p-2 space-y-2 overflow-y-auto">
          <div
            v-for="session in chatStore.sessions"
            :key="session.id"
            @click="chatStore.switchSession(session.id); showMobileSessions = false"
            :class="[
              'p-3 rounded-lg cursor-pointer transition-all duration-200',
              {
                'bg-primary-50 dark:bg-primary-900/20': chatStore.currentSession?.id === session.id,
                'hover:bg-gray-50 dark:hover:bg-dark-700': chatStore.currentSession?.id !== session.id
              }
            ]"
          >
            <p class="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
              {{ session.title }}
            </p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {{ formatTime(session.updated_at) }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { useChatStore } from '@/store/chat'
import { useAppStore } from '@/store/app'
import { useThemeStore } from '@/store/theme'
import DataTable from '@/components/DataTable.vue'
import VexTable from '@/components/VexTable.vue'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// Icons
import {
  PlusIcon,
  PaperAirplaneIcon,
  TrashIcon,
  Bars3Icon,
  XMarkIcon,
  ClipboardIcon,
  ArrowPathIcon,
  CpuChipIcon,
  ChatBubbleOvalLeftEllipsisIcon,
  ChartBarIcon,
  TableCellsIcon,
  UserGroupIcon,
  ShoppingCartIcon,
  CubeIcon
} from '@heroicons/vue/24/outline'

const chatStore = useChatStore()
const appStore = useAppStore()
const themeStore = useThemeStore()

// Refs
const messagesContainer = ref<HTMLElement>()
const messageInput = ref<HTMLTextAreaElement>()

// Local state
const messageText = ref('')
const showMobileSessions = ref(false)
const loadingMore = ref(false)

// Quick actions for welcome screen
const quickActions = [
  {
    title: '查看数据概览',
    description: '获取系统总体数据统计',
    message: '帮我查看一下系统的数据概览，包括产品、客户、订单等基本信息',
    icon: ChartBarIcon
  },
  {
    title: '销售订单分析',
    description: '分析近期销售情况',
    message: '帮我分析一下近七天的销售订单数据，并生成可视化图表',
    icon: ShoppingCartIcon
  },
  {
    title: '库存管理',
    description: '检查库存状态',
    message: '查看当前库存情况，特别是低库存的产品',
    icon: CubeIcon
  },
  {
    title: '客户管理',
    description: '客户数据分析',
    message: '分析客户数据，找出活跃客户和潜在客户',
    icon: UserGroupIcon
  },
  {
    title: '表格操作',
    description: '查看系统表格',
    message: '显示系统中有哪些数据表格',
    icon: TableCellsIcon
  },
  {
    title: '系统设置',
    description: '配置和管理',
    message: '我想了解系统的配置选项和管理功能',
    icon: CpuChipIcon
  }
]

// Methods
const sendMessage = async () => {
  if (!messageText.value.trim() || chatStore.loading) return

  const message = messageText.value.trim()
  messageText.value = ''
  
  // Reset textarea height
  if (messageInput.value) {
    messageInput.value.style.height = 'auto'
  }

  // 立即滚动到底部显示用户消息
  scrollToBottom(false)
  
  try {
    await chatStore.sendMessage(message)
    // 发送完成后再次滚动到底部显示AI回复
    scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
    scrollToBottom()
  }
}

const sendQuickMessage = async (message: string) => {
  messageText.value = message
  await sendMessage()
}

const newLine = () => {
  messageText.value += '\n'
  nextTick(() => adjustTextareaHeight())
}

// 导出表格数据
const exportTableData = (tableData: any) => {
  console.log('导出数据:', tableData)
  // TODO: 实现CSV导出功能
}

// 导出动态表格数据
const exportDynamicTableData = (tableData: any) => {
  console.log('导出动态表格数据:', tableData)
  // TODO: 实现基于表格配置的CSV导出功能
}

// 处理行点击
const handleRowClick = (row: any) => {
  console.log('点击行:', row)
  // TODO: 实现行详情查看
}

// 格式化表格列配置
const formatTableColumns = (columns: any[]) => {
  if (!columns || !Array.isArray(columns)) {
    return []
  }
  
  return columns.map(col => ({
    field: col.key,
    title: col.title,
    width: col.width,
    sortable: col.sortable,
    type: getVexTableColumnType(col.value_type),
    fixed: col.fixed,
    align: 'left',
    headerAlign: 'center',
    showOverflow: true,
    formatter: getColumnFormatter(col.value_type, col.render_type)
  }))
}

// 获取VEX TABLE列类型
const getVexTableColumnType = (valueType: string) => {
  const typeMap: Record<string, string> = {
    'number': 'number',
    'currency': 'number', 
    'date': 'date',
    'datetime': 'datetime',
    'boolean': 'checkbox',
    'text': 'string',
    'tag': 'string',
    'select': 'string'
  }
  return typeMap[valueType] || 'string'
}

// 获取列格式化器
const getColumnFormatter = (valueType: string, renderType?: string) => {
  return ({ cellValue }: any) => {
    if (cellValue === null || cellValue === undefined) {
      return '-'
    }
    
    switch (valueType) {
      case 'currency':
        return `¥${Number(cellValue).toLocaleString()}`
      case 'date':
        return new Date(cellValue).toLocaleDateString()
      case 'datetime':
        return new Date(cellValue).toLocaleString()
      case 'boolean':
        return cellValue ? '是' : '否'
      case 'tag':
        return formatTagValue(cellValue, renderType)
      default:
        return cellValue
    }
  }
}

// 格式化标签值
const formatTagValue = (value: any, renderType?: string) => {
  if (!renderType) return value
  
  const tagMaps: Record<string, Record<string, string>> = {
    'status_tag': {
      'active': '启用',
      'inactive': '禁用'
    },
    'order_status_tag': {
      'pending': '待处理',
      'confirmed': '已确认',
      'shipped': '已发货',
      'delivered': '已送达',
      'cancelled': '已取消'
    },
    'payment_status_tag': {
      'unpaid': '未支付',
      'paid': '已支付',
      'refunded': '已退款'
    }
  }
  
  return tagMaps[renderType]?.[value] || value
}

// 生成图表
const generateChart = (tableData: any) => {
  console.log('生成图表:', tableData)
  // 自动发送图表生成指令
  sendQuickMessage(`根据 ${tableData.title} 的数据生成可视化图表`)
}

const adjustTextareaHeight = () => {
  if (!messageInput.value) return
  
  messageInput.value.style.height = 'auto'
  const minHeight = 48 // min-h-[48px]
  const maxHeight = 128 // max-h-32
  const newHeight = Math.max(Math.min(messageInput.value.scrollHeight, maxHeight), minHeight)
  messageInput.value.style.height = newHeight + 'px'
}

const scrollToBottom = (smooth = true) => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: smooth ? 'smooth' : 'auto'
      })
    }
  })
}

const handleScroll = async (event: Event) => {
  const container = event.target as HTMLElement
  if (!container || loadingMore.value) return

  // 检查是否滚动到顶部附近（距离顶部小于100px）
  if (container.scrollTop < 100) {
    loadingMore.value = true
    
    try {
      // 保存当前滚动位置
      const oldScrollHeight = container.scrollHeight
      const oldScrollTop = container.scrollTop
      
      // 加载更多消息
      const hasMore = await chatStore.loadMoreMessages()
      
      if (hasMore) {
        // 恢复滚动位置，保持用户看到的内容不变
        nextTick(() => {
          const newScrollHeight = container.scrollHeight
          const scrollDiff = newScrollHeight - oldScrollHeight
          container.scrollTop = oldScrollTop + scrollDiff
        })
      }
    } catch (error) {
      console.error('加载更多消息失败:', error)
    } finally {
      loadingMore.value = false
    }
  }
}

const formatTime = (date: Date | string | null | undefined) => {
  if (!date) return '未知时间'
  
  let dateObj: Date
  
  if (typeof date === 'string') {
    dateObj = new Date(date)
  } else if (date instanceof Date) {
    dateObj = date
  } else {
    return '未知时间'
  }
  
  // 检查日期是否有效
  if (isNaN(dateObj.getTime())) {
    return '未知时间'
  }
  
  try {
    return formatDistanceToNow(dateObj, { 
      addSuffix: true,
      locale: zhCN
    })
  } catch (error) {
    console.warn('时间格式化失败:', error, date)
    return '未知时间'
  }
}

const formatMessageContent = (content: string) => {
  // 安全检查输入
  if (!content || typeof content !== 'string') {
    return content || ''
  }
  
  // Enhanced markdown formatting with table support
  let formatted = content
  
  // Convert tables
  formatted = formatMarkdownTables(formatted)
  
  // Convert other markdown elements
  formatted = formatted
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code class="bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-sm">$1</code>')
    .replace(/^# (.*$)/gm, '<h1 class="text-2xl font-bold mb-4 text-gray-900 dark:text-gray-100">$1</h1>')
    .replace(/^## (.*$)/gm, '<h2 class="text-xl font-bold mb-3 text-gray-900 dark:text-gray-100">$1</h2>')
    .replace(/^### (.*$)/gm, '<h3 class="text-lg font-bold mb-2 text-gray-900 dark:text-gray-100">$1</h3>')
    .replace(/^\* (.*$)/gm, '<li class="ml-4">$1</li>')
    .replace(/^(\d+)\. (.*$)/gm, '<li class="ml-4">$1. $2</li>')
    .replace(/\n/g, '<br>')
  
  // Wrap list items
  formatted = formatted.replace(/(<li.*?<\/li>)/g, '<ul class="list-disc mb-4">$1</ul>')
  
  return formatted
}

const formatMarkdownTables = (content: string) => {
  // 安全检查输入
  if (!content || typeof content !== 'string') {
    return content || ''
  }
  
  // Split content by lines to process tables
  const lines = content.split('\n')
  let result = []
  let inTable = false
  let tableRows = []
  
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    
    // Check if line is a table row (contains |)
    if (line.includes('|') && line.length > 2) {
      if (!inTable) {
        inTable = true
        tableRows = []
      }
      tableRows.push(line)
    } else {
      // If we were in a table, process it
      if (inTable && tableRows.length > 0) {
        result.push(convertTableToHTML(tableRows))
        tableRows = []
        inTable = false
      }
      result.push(line)
    }
  }
  
  // Handle table at end of content
  if (inTable && tableRows.length > 0) {
    result.push(convertTableToHTML(tableRows))
  }
  
  return result.join('\n')
}

const convertTableToHTML = (tableRows: string[]) => {
  if (!tableRows || tableRows.length < 2) return (tableRows || []).join('\n')
  
  let html = '<div class="overflow-x-auto my-4"><table class="min-w-full border-collapse border border-gray-300 dark:border-gray-600">'
  
  // Header row - 安全检查
  const headerRow = tableRows[0]
  if (!headerRow || typeof headerRow !== 'string') {
    return tableRows.join('\n')
  }
  
  const headerCells = headerRow.split('|').map(cell => cell.trim()).filter(cell => cell)
  if (headerCells.length === 0) {
    return tableRows.join('\n')
  }
  
  html += '<thead class="bg-gray-50 dark:bg-gray-700"><tr>'
  headerCells.forEach(cell => {
    html += `<th class="border border-gray-300 dark:border-gray-600 px-3 py-2 text-left font-semibold text-gray-900 dark:text-gray-100">${cell}</th>`
  })
  html += '</tr></thead>'
  
  // Skip separator row (usually contains --- or similar)
  html += '<tbody>'
  for (let i = 2; i < tableRows.length; i++) {
    const row = tableRows[i]
    if (!row || typeof row !== 'string') continue
    
    const cells = row.split('|').map(cell => cell.trim()).filter(cell => cell)
    if (cells.length > 0) {
      html += '<tr class="hover:bg-gray-50 dark:hover:bg-gray-600">'
      cells.forEach(cell => {
        html += `<td class="border border-gray-300 dark:border-gray-600 px-3 py-2 text-gray-900 dark:text-gray-100">${cell}</td>`
      })
      html += '</tr>'
    }
  }
  html += '</tbody></table></div>'
  
  return html
}

const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    appStore.showSuccess('消息已复制到剪贴板')
  } catch (err) {
    appStore.showError('复制失败')
  }
}

const retryMessage = async () => {
  await chatStore.retryLastMessage()
  scrollToBottom()
}

const clearChat = async () => {
  if (!chatStore.hasMessages) return
  
  if (confirm('确定要清空当前对话吗？此操作不可撤销。')) {
    await chatStore.clearCurrentSession()
    appStore.showSuccess('对话已清空')
  }
}

const deleteSession = async (sessionId: string) => {
  if (confirm('确定要删除这个对话吗？此操作不可撤销。')) {
    await chatStore.deleteSession(sessionId)
    appStore.showSuccess('对话已删除')
  }
}

// 监听消息变化，自动滚动到底部
watch(() => chatStore.currentMessages, () => {
  scrollToBottom()
}, { deep: true })

// 监听打字状态变化
watch(() => chatStore.typing, (typing) => {
  if (typing) {
    scrollToBottom()
  }
})

// Lifecycle
onMounted(async () => {
  try {
    await chatStore.initialize()
    scrollToBottom(false)
    
    // Focus on input
    if (messageInput.value) {
      messageInput.value.focus()
    }
    
    // Ensure app loading is cleared when chat loads
    appStore.setLoading(false)
  } catch (error) {
    console.error('Chat initialization failed:', error)
    appStore.setLoading(false)
  }
})

onUnmounted(() => {
  // Cleanup if needed
})
</script>

<style scoped>
/* 动态表格样式 */
.dynamic-table-container {
  @apply bg-white dark:bg-dark-800 rounded-lg border border-gray-200 dark:border-dark-600 overflow-hidden;
}

.table-header {
  @apply px-4 py-3 bg-gray-50 dark:bg-dark-700 border-b border-gray-200 dark:border-dark-600;
}

/* Typing dots animation */
.typing-dots::after {
  content: '...';
  animation: typingDots 1.5s infinite;
}

@keyframes typingDots {
  0%, 20% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

/* Smooth scrolling for messages */
.overflow-y-auto {
  scroll-behavior: smooth;
}

/* Custom scrollbar for messages */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: rgba(156, 163, 175, 0.5);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: rgba(156, 163, 175, 0.7);
}

/* Message animations */
.animate-slide-up {
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Markdown content styling */
.markdown-content {
  @apply text-gray-900 dark:text-gray-100;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3 {
  @apply font-bold text-gray-900 dark:text-gray-100;
}

.markdown-content table {
  @apply border-collapse border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden;
}

.markdown-content th {
  @apply bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 px-3 py-2 text-left font-semibold text-gray-900 dark:text-gray-100;
}

.markdown-content td {
  @apply border border-gray-300 dark:border-gray-600 px-3 py-2 text-gray-900 dark:text-gray-100;
}

.markdown-content tr:hover {
  @apply bg-gray-50 dark:bg-gray-600;
}

.markdown-content ul {
  @apply list-disc pl-6 mb-4;
}

.markdown-content ol {
  @apply list-decimal pl-6 mb-4;
}

.markdown-content li {
  @apply mb-1 text-gray-900 dark:text-gray-100;
}

.markdown-content code {
  @apply bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded text-sm font-mono;
}

.markdown-content strong {
  @apply font-bold text-gray-900 dark:text-gray-100;
}

.markdown-content em {
  @apply italic text-gray-700 dark:text-gray-300;
}
</style>
